class WidgaryTagLib {

    static namespace = "wa"


    
    def ifDevEnv = { attrs, body ->
        def map = grailsApplication.metadata
        String env = map[grailsApplication.ENVIRONMENT]
        if (env == grailsApplication.ENV_DEVELOPMENT) {
            out << body()
        }
    }

    // if pagination...
    def ifPaginate = { attrs, body ->
        def count = attrs.count
        if (params.max && params.max < count) {
            out << body()
        }
    }
    
    // if person logged in...    
    def ifUser = { attrs, body ->
        boolean valid = session.personId != null
        if (attrs.not) {
            valid = !valid
        }
        if (valid) {
            out << body()
        }
    }
    
    // if user same as logged in user...
    def ifSameUser = { attrs, body ->
        boolean valid = session.personId && session.personId == attrs.id
        if (attrs.not) {
            valid = !valid
        }
        if (valid) {
            out << body()
        }
    }
    
    // if logged in user owns this item...
    def ifCurrentUserOwns = { attrs, body ->
        boolean valid = session.personId && session.personId == attrs.id
        if (attrs.not) {
            valid = !valid
        }
        if (valid) {
            out << body()
        }
    }


    // if logged in user has widgets...
    def ifUserHasWidgets = { attrs, body ->
        boolean valid = session.widgetsCount && session.widgetsCount > 0
        if (attrs.not) {
            valid = !valid
        }
        if (valid) {
            out << body()
        }
    }

    // XXX I am dissapointed that id and name couldn't be
    //     extracted from the context, and had to be included in attrs.
    def iwgCtlLink = { attrs ->
        attrs.action     = "ctrliwg"
        attrs.controller = "widget"


        out << "<a href=\"${createLink(attrs).encodeAsHTML()}" + ".iwg" +"\">"  // XXX .iwg should be avoided!
        out << "[Download]" // XXX Should be "name-link, but for some reason the param doesn't get through right ;(
        out << "</a>"
    }
    
    def userLink = { attrs ->
		def person = Person.get(session.personId)
        attrs.controller = 'person'
        attrs.action = 'show'
        attrs.id = person.id
        out << "<a href=\"${createLink(attrs).encodeAsHTML()}\""
        // process remaining attributes
        attrs.each { key, value ->
            out << " $key=\"$value\""
        }
        out << '>'
        out << person.name.encodeAsHTML()
        out << '</a>'
    }
}
